<?php
class IG_Data_Plugin_Param extends IG_Data_Plugin
{
    protected $_params = array();
    protected $_diaplay = true;

    public function __construct($config = array())
    {
        if (isset($config['display'])) {
            $this->_diaplay = (bool) $config['display'];
            unset($config['display']);
        }

        $this->_params += $config;
    }

    public function before()
    {
        $return = $this->_eachParams();

        $this->getView()->assign('params', $this->_params);
        if ($this->_diaplay) {
            echo $this->getView()->render('param.phtml');
        }
        return $return;
    }

    public function beforeXmlHttpRequest()
    {
        $this->_eachParams();
    }

    protected function _eachParams()
    {
        $return = true;
        $requestParams = $this->getRequest()->getParam('params', array());
        $sourceParams = array();
        foreach ($this->_params as $key => & $param) {
            if (isset($requestParams[$key]) && $requestParams[$key] !== '') {
                $param['value'] = $requestParams[$key];
            } else if (isset($param['default'])){
                $param['value'] = $param['default'];
            } else {
                $return = false;
                $param['value'] = null;
                continue;
            }
            $sourceParams[$key] = $param['value'];
        }
        $this->getSource()->setParams($sourceParams);
        return $return;
    }
}